/*
 * @Description: 
 * @Author: zhanyinjia
 * @Date: 2022-12-12 14:31:46
 * @LastEditors: zhanyinjia
 * @LastEditTime: 2022-12-12 15:30:09
 */
import JSZip from 'jszip'
import XLSXStyle from 'xlsx-style'
import FileSaver from 'file-saver'

const exportZip = (zipName = "example.zip", list) => {
  // 生成excel的配置项
  const wopts = {
    bookType: 'xlsx', // 要生成的文件类型
    bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
    type: 'binary'
    // showGridLines: false
  };

  const zip = new JSZip();

  list.forEach(e => {
    const workbook = e.sheetList.reduce((prev, next) => {
      prev.SheetNames.push(next.sheetName)
      prev.Sheets[next.sheetName] = next.sheet
      return prev
    }, {
      SheetNames: [],
      Sheets: {}
    })

    // 这里要调用XLSXStyle.write，因为设置了单元格样式，如果用XLSX.write则单元格样式设置无效
    const wbout = XLSXStyle.write(workbook, wopts);
    const blob = new Blob([s2ab(wbout)], { type: "application/octet-stream" });
    zip.file(e.fileName, blob)
  });
  zip.generateAsync({ type: "blob" })
    .then(function (content) {
      // see FileSaver.js
      FileSaver.saveAs(content, zipName)
    });
}

// 字符串转ArrayBuffer
const s2ab = (s) => {
  var buf = new ArrayBuffer(s.length);
  var view = new Uint8Array(buf);
  for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  return buf;
}

export {
  exportZip
}